import MyIcon from '@/components/MyIcon';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { loopArray } from '@/utils';
import { AutoComplete, Card, Col, Empty, Input, Row } from 'antd';
import React, { ChangeEvent, useContext, useMemo } from 'react';
import { UserManageContext, UserOtherHandleContext } from '../hooks';
import { IUserAddOrEditPosRight } from '../type';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import cls from 'classnames';

export const UserAddOrEditPosRight: React.FC<IUserAddOrEditPosRight> = () => {
  const { leftTreeData, userFixCls } = useContext(UserManageContext);
  const {
    userOthDispatch,
    twoLeftSelectKeys,
    twoLeftSelectRows,
    secopeRightSearValue,
  } = useContext(UserOtherHandleContext);

  // 搜索下拉菜单
  const autoOptionRight = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if ((item?.name || item?.text)?.includes(secopeRightSearValue)) {
          // const name = item?.name || item?.text;
          // const nameLength = name?.length;
          // const select = name?.search(secopeRightSearValue);
          // const searchLength = secopeRightSearValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = secopeRightSearValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name || item?.text,
            key: item?.id,
            label: (
              <div>
                {/* <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span> */}
                <span>{item?.name || item?.text}</span>
                {item?.isOpen == 0 || item?.open == false ? (
                  <span style={{ color: 'red' }}>（禁用）</span>
                ) : (
                  ''
                )}
              </div>
            ),
          });
        }
      });
    };
    tileTreeData(twoLeftSelectRows);
    return option;
  }, [twoLeftSelectRows, secopeRightSearValue]);

  // 搜索框改变
  const onInputChangeRight = (e: ChangeEvent<HTMLInputElement>) => {
    userOthDispatch({
      type: 'otherHandle-secopeRightSearValue',
      payload: e.target.value,
    });
  };

  // 点击搜索
  const onAutoSelectRight = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    userOthDispatch({
      type: 'otherHandle-secopeRightSearValue',
      payload: value,
    });

    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);

    //   resolve(optionId);
    // });
    // promise.then(() => {
    // });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'userCardRight');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 左侧可以选择的数据
  const leftOkCheckLength = () => {
    let nodeList = loopArray(leftTreeData);
    let onCheckList = nodeList?.filter((item: any) => {
      return item?.textType == 2 && item?.open == true;
    });
    return onCheckList?.length;
  };

  // 右侧点击删除
  const delRightTag = (tabObj: any) => {
    let treeKeys = twoLeftSelectKeys?.filter((itemKey: string) => {
      return tabObj?.id != itemKey;
    });
    let treeRows = twoLeftSelectRows?.filter((itemRow: any) => {
      return tabObj?.id != itemRow?.id;
    });
    userOthDispatch({
      type: 'otherHandle-twoLeftSelectKeys',
      payload: treeKeys,
    });
    userOthDispatch({
      type: 'otherHandle-twoLeftSelectRows',
      payload: treeRows,
    });
  };

  return (
    <>
      <Col span={11}>
        <Card
          className={userFixCls + 'userSecopeCard'}
          bordered
          title={
            <>
              <Row style={{ display: 'flex', alignItems: 'center' }}>
                <Col span={8}>
                  已选： {twoLeftSelectRows?.length} / {leftOkCheckLength()}
                </Col>
                <Col span={16}>
                  <AutoComplete
                    style={{ width: '100%' }}
                    options={autoOptionRight}
                    notFoundContent={
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    }
                    onSelect={onAutoSelectRight}
                  >
                    <Input
                      suffix={<SearchOutlined />}
                      onChange={onInputChangeRight}
                      placeholder="请按名称搜索"
                      allowClear={true}
                    />
                  </AutoComplete>
                </Col>
              </Row>
            </>
          }
        >
          <ScrollBarLayout
            style={{
              padding: '10px 0px',
              height: document.body.clientHeight * 0.4,
            }}
          >
            <div style={{ paddingBottom: '10px' }}>
              {twoLeftSelectRows && twoLeftSelectRows.length > 0 ? (
                <>
                  {twoLeftSelectRows.map((item: any, index: any) => {
                    const name = item?.name ?? item?.text;
                    const nameLength = name?.length;
                    const select = name?.search(secopeRightSearValue);
                    const searchLength = secopeRightSearValue?.length;
                    const afterStr = name?.slice(0, select);
                    const selectStr = secopeRightSearValue;
                    const beforeStr = name?.slice(
                      select + searchLength,
                      nameLength,
                    );
                    const titleTree =
                      select > -1 && selectStr ? (
                        <span>
                          {afterStr}
                          <span style={{ color: '#f50' }}>{selectStr}</span>
                          {beforeStr}
                        </span>
                      ) : (
                        item?.name ?? item?.text
                      );
                    return (
                      <div
                        style={{ paddingTop: index == 0 ? '0px' : '' }}
                        className={cls(
                          userFixCls + 'userSecopeCard-rightFather',
                        )}
                        id={item?.id + 'userCardRight'}
                        key={item?.id + 'userCardRight'}
                      >
                        <div
                          className={
                            item?.isOpen == 0 || item?.open == false
                              ? userFixCls + 'userSecopeCard-rightChildFalse'
                              : userFixCls + 'userSecopeCard-rightChild'
                          }
                        >
                          <div
                            className={cls(
                              userFixCls + 'userSecopeCard-rightChildIcon',
                            )}
                          >
                            <div style={{ margin: '0px 5px 0px 10px' }}>
                              {item?.textType == 0 && (
                                <MyIcon type={'icon-bank'} />
                              )}
                              {item?.textType == 1 && (
                                <MyIcon type={'icon-cluster'} />
                              )}
                              {item?.textType == 2 && (
                                <MyIcon type={'icon-icon_lingdaopishi'} />
                              )}
                            </div>
                            <div style={{ padding: '5px 0px' }}>
                              {titleTree ?? '--'}
                              {item?.isOpen == 0 || item?.open == false ? (
                                <span>（禁用）</span>
                              ) : (
                                ''
                              )}
                            </div>
                          </div>
                          <span
                            style={{
                              margin: '0px 10px',
                              cursor: 'pointer',
                            }}
                            onClick={(e) => {
                              e?.stopPropagation();
                              delRightTag(item);
                            }}
                          >
                            <CloseOutlined />
                          </span>
                        </div>
                      </div>
                    );
                  })}
                </>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </div>
          </ScrollBarLayout>
        </Card>
      </Col>
    </>
  );
};
